package com.hanko.rabbitmq;

import cn.hutool.core.date.DateUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author : Hanko
 * @CreateTime : 2019/9/3
 * @Description :
 **/
@Component
@RequiredArgsConstructor
public class SendMessage {

    //使用RabbitTemplate,这提供了接收/发送等等方法
    private  final RabbitTemplate rabbitTemplate;

    /**
     * 生产者要保证消息正确的被发送到MQ
     * 主要通过rabbitTemplate来确认
     *
     */
    public void sendMessage() {
        setupCallbacks();
        String messageId = String.valueOf(UUID.randomUUID());
        String messageData = "Test message, hello!";
        String createTime = DateUtil.now();
        Map<String,Object> map=new HashMap<>();
        map.put("messageId",messageId);
        map.put("messageData",messageData);
        map.put("createTime",createTime);
        //将消息携带绑定键值：TestDirectRouting 发送到交换机TestDirectExchange
        rabbitTemplate.convertAndSend("Hanko-DirectExchange", "Hanko-DirectRouting1", map);
    }

    private void setupCallbacks() {
        //confirm机制是只保证消息到达exchange，并不保证消息可以路由到正确的queue
        this.rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            System.out.println("ConfirmCallback:     " + "相关数据：" + correlationData);
            System.out.println("ConfirmCallback:     " + "确认情况：" + ack);
            System.out.println("ConfirmCallback:     " + "原因：" + cause);
        });

        //当前的exchange不存在或者指定的路由key路由不到才会触发return机制
        this.rabbitTemplate.setReturnsCallback((returned) -> {
            System.out.println("ReturnCallback:     " + "消息：" + returned.getMessage());
            System.out.println("ReturnCallback:     " + "回应码：" + returned.getReplyCode());
            System.out.println("ReturnCallback:     " + "回应信息：" + returned.getReplyText());
            System.out.println("ReturnCallback:     " + "交换机：" + returned.getExchange());
            System.out.println("ReturnCallback:     " + "路由键：" + returned.getRoutingKey());
        });
    }
    }
